package com.studentapp.tool;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.studentapp.bean.LoginGsonBean;

import java.lang.reflect.Type;

import static android.content.Context.MODE_PRIVATE;

public class StudentSpTool {
    SharedPreferences sp;
    SharedPreferences.Editor editor;

    /**
     * 构造方法
     * @param context 上下文
     */
    public StudentSpTool(Context context) {
        sp = context.getSharedPreferences("config", MODE_PRIVATE);
        editor = sp.edit();
    }

    /**
     * 将登陆的用户的数据存入sp
     * @param student
     */
    public void putStudentBean(LoginGsonBean.DataBean student) {
        Gson gson = new Gson();
        String json = gson.toJson(student);
        editor.putString("userData", json);
        editor.commit();
    }

    /**
     * 获取学生数据
     * @return 学生类
     */
    public LoginGsonBean.DataBean getStudentBean() {
        Gson gson = new Gson();
        String json = sp.getString("userData", null);
        /*Type type = new TypeToken<List<BookBean>>() {
        }.getType();*/
        Type type = new TypeToken<LoginGsonBean.DataBean>() {
        }.getType();

        LoginGsonBean.DataBean userData = gson.fromJson(json, type);
        return userData;
    }
}
